<?php


namespace App\Services\Home;

use App\Models\Client;
use App\Models\ClientTask;

class ClientTaskService
{
    /**
     * 获取keepa产品信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTaskProduct($params)
    {
        //处理请求参数
        $rank_range = explode('~', $params['sales_rank_range']);

        //检查请求来源是否为已注册是站点
        $client = Client::where('client_url', $params['host'])->first();
        if (!$client){
            return Error('该站点未授权，不可申请获取产品！');
        }

        //自动生成任务记录
        $task_record = [
            'domain_id' => $params['domain_id'],
            'cat_id' => $params['cat_id'],
            'sales_rank_low' => (int)$rank_range[0],
            'sales_rank_high' => (int)$rank_range[1],
            'request_url' => $params['host'],
            'client_task_id' => $params['client_task_id'],
            'counts' => $params['counts'],
            'recent_update' => $params['recent_update'],
            'client_create_time' => $params['client_create_time'],
            'status' => 'wait'
        ];
        $record = ClientTask::create($task_record);

        //运行py
        $this->run_py($record->_id);
        return Success('产品信息抓取中，请耐心等待...', $record);
    }

    /**
     * 运行py获取产品信息，后台运行无实时返回
     * @param $filter
     */
    private function run_py($filter){
        $pythonScriptPath = base_path('app/PythonScripts/client_product.py'); // 脚本的完整路径
        pclose(popen("nohup python {$pythonScriptPath} {$filter} > /dev/null 2>&1 &", 'r'));  // 使用 popen 启动 Python 脚本，'&' 将其放到后台执行
    }
}
